#include "privatechat.h"
#include "ui_privatechat.h"
#include "tcpclient.h"
#include <QTextEdit>
#include <QMessageBox>

PrivateChat::PrivateChat(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::PrivateChat)
{
    ui->setupUi(this);
}

PrivateChat::~PrivateChat()
{
    delete ui;
}

void PrivateChat::set_name(QString name)
{
    this->other_name = name;
    this->my_name = TcpClient::getInstance().get_login_name();
}

PrivateChat &PrivateChat::getInstance()
{
    static PrivateChat ret;
    return ret;
}

void PrivateChat::update_msg(const PDU *pdu)
{
    QString msg = QString("[%1]say: %2").arg(pdu->caData).arg((char*)pdu->caMsg);
    ui->textEdit->append(msg);
}

void PrivateChat::on_pushButton_clicked()
{
    // QString msg = ui->textEdit->toPlainText();
    QString msg = ui->lineEdit->text();
    ui->lineEdit->clear();
    if (!msg.isEmpty()) {

        PDU* pdu = makePDU(msg.size()+1); //注册的实际消息长度=0
        pdu->uiMsgType = ENUM_MSG_TYPE_SEND_MSG_REQUEST;
        strncpy(pdu->caData, my_name.toStdString().c_str(), 32);
        strncpy(pdu->caData+32, other_name.toStdString().c_str(), 32);
        strcpy((char*)pdu->caMsg, msg.toStdString().c_str());

        TcpClient::getInstance().getTcpSocket().write((char*)pdu, pdu->uiPDULen); //socket 发送
        // pdu->printPDU();
        free(pdu);
        pdu = NULL;
        ui->lineEdit->clear();
    } else {
        QMessageBox::information(this, "发送信息为空", "请输入信息后在发送");
    }
}

